// @Author : zaniu(zzaniu@126.com)
// @Time   : 2021/9/5 22:43
// @Desc   :
//
//                   _ooOoo_
//                  o8888888o
//                  88" . "88
//                  (| -_- |)
//                  O\  =  /O
//               ____/`---'\____
//             .'  \\|     |//  `.
//            /  \\|||  :  |||//  \
//           /  _||||| -:- |||||-  \
//           |   | \\\  -  /// |   |
//           | \_|  ''\---/''  |   |
//           \  .-\__  `-`  ___/-. /
//         ___`. .'  /--.--\  `. . __
//      ."" '<  `.___\_<|>_/___.'  >'"".
//     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//     \  \ `-.   \_ __\ /__ _/   .-` /  /
// =====`-.____`-.___\_____/___.-`____.-'=====
//                   `=---='
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//           佛祖保佑       永无BUG
//
package middleware

import (
	"context"
	"distributedTransaction/client/conf"
	"distributedTransaction/proto2go"
	"fmt"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"net/http"
	"strings"
)

func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 通过http header中的token解析来认证
		token := c.Request.Header.Get("token")
		if token == "" {
			c.JSON(http.StatusForbidden, gin.H{
				"message": "请求未携带token，无权限访问",
			})
			c.Abort()
			return
		}
		tokenSlice := strings.Split(token, " ")
		if len(tokenSlice) != 2 || tokenSlice[0] != "bt" || tokenSlice[1] == "" {
			c.JSON(http.StatusForbidden, gin.H{
				"message": "无效的token",
			})
			c.Abort()
			return
		}
		rpcServerInfo, err := conf.GetOneRpcServerInfo(conf.GlobalUserServices)
		if err != nil {
			panic(err)
		}
		userCoon, err := grpc.Dial(fmt.Sprintf("%s:%d", rpcServerInfo.Ip, rpcServerInfo.Port), grpc.WithInsecure())
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"message": "RPC调用失败",
			})
			c.Abort()
			return
		}
		defer userCoon.Close()
		userClient := proto2go.NewUserClient(userCoon)
		res, err := userClient.AuthToken(context.Background(), &proto2go.AuthRequest{Token: tokenSlice[1]})
		if err != nil {
			c.JSON(http.StatusForbidden, gin.H{
				"message": "无效的token",
			})
			c.Abort()
			return
		}
		c.Set("user", res.UserName)
	}
}
